package cash.cmp.personal_financial_system.controller;

import cash.cmp.personal_financial_system.model.Bill;
import cash.cmp.personal_financial_system.utils.Result;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/ocr")
public class Ocr {

    @PostMapping("/train")
    public Result train(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONObject result = (JSONObject) jsonObject.get("result");
        List<Object> item_list = (List<Object>) result.get("item_list");
        System.out.println(item_list);

        Bill bill = new Bill();

        bill.setBillType(1);
        JSONObject tmpJson11 = (JSONObject) item_list.get(11);
        if("火车票ID".equals(tmpJson11.get("description")) ){
            JSONObject tmpJson7 = (JSONObject) item_list.get(7);
            String value7 = (String) tmpJson7.get("value");
            bill.setMoney( Double.parseDouble(value7) );
            bill.setType("交通");
            JSONObject tmpJson5 = (JSONObject) item_list.get(5);
            String value5 = (String) tmpJson5.get("value");

            JSONObject tmpJson10 = (JSONObject) item_list.get(10);
            String value10 = (String) tmpJson10.get("value");
            bill.setRemark("乘车人："  + value10  + "，乘车时间：" + value5 );
        }else{
            Result.fail(520,"fail","不是火车票的图片");
        }
        return Result.succ(200,"success",bill);
    }

    @PostMapping("/normal")
    public Result normal(@RequestBody String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONObject result = (JSONObject) jsonObject.get("result");
        JSONArray lines = (JSONArray) result.get("lines");

        /**
         "当前状态"关键字 --> 表示微信支付详情页
         "付款方式"关键字 --> 表示支付宝支付详情页
         "饿了么"关键字  --> 表示支饿了么账单详情页
         */
        Bill bill = null;
        boolean flag = false;
        for(int i = 0; i < 10; i++) {
            String text = (String) lines.getJSONObject(i).get("text");
            if(text.contains("当前状态")) {
                // 微信支付详情页,获取信息
                bill = wxBill(i, lines);
                flag = true;
                break;
            }
            if(text.contains("交易成功") || text.contains("自动扣款成功")){
                // 支付宝支付详情页,获取信息
                bill = AlipayBill(i, lines);
                flag = true;
                break;
            }
            String beforeText = null;
            if(i > 0) {
                beforeText = (String) lines.getJSONObject(i - 1).get("text");
            }
            if( ( text.contains("饿了么") && (text.contains("＃") || text.contains("#")) ) || (text.contains("饿了么") && ( beforeText.contains("＃") ||beforeText.contains("#")) ) ){
                // 饿了么账单详情页,获取信息
                bill = elmBill(i, lines);
                flag = true;
                break;
            }
        }
        System.out.println(bill);
        if(!flag) {
            return Result.succ(521, "fail", "目前不支持此类图片账单识别");
        }else{
            return Result.succ(200, "success", bill);
        }
    }

    @PostMapping("/binary")
    public Result binary(@RequestParam("file") MultipartFile file) {
        byte[] bytes;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.succ(200, "success", bytes);
    }

    public Bill wxBill(int index, JSONArray lines) {
        Bill bill = new Bill();


        String moneyStr = (String) lines.getJSONObject(index - 1).get("text");
        if( '-' == moneyStr.charAt(0) ) {
            bill.setBillType(1);
        }else{
            bill.setBillType(0);
        }

        String tmp = moneyStr.replace("+", "");
        String money = tmp.replace("-", "");
        bill.setMoney( Double.parseDouble(money) );

        String dataStr = (String) lines.getJSONObject(index + 3).get("text");
        Date time;
        try {
            // 2023年2月11日 20：03：26
            time = new SimpleDateFormat("yyyy年MM月dd日 HH：mm：ss").parse(dataStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        bill.setTime(time);

        String shopName = "商品：" + lines.getJSONObject(index + 5).get("text");
        if( !"商户全称".equals(lines.getJSONObject(index + 6).get("text")) ) {
            bill.setRemark(shopName + lines.getJSONObject(index + 6).get("text"));
        }else {
            bill.setRemark(shopName);
        }
        return bill;
    }

    public Bill AlipayBill(int index, JSONArray lines) {
        Bill bill = new Bill();
        String moneyStr = (String) lines.getJSONObject(index - 1).get("text");
        if( '-' == moneyStr.charAt(0) ) {
            bill.setBillType(1);
        }else{
            bill.setBillType(0);
        }

        String tmp = moneyStr.replace("+", "");
        String money = tmp.replace("-", "");
        bill.setMoney( Double.parseDouble(money) );

        for(int i = index + 3; i < lines.size(); i++) {
            String text = (String) lines.getJSONObject(i).get("text");
            if(text.contains("商品说明")) {
                bill.setRemark( "商品说明" + (String) lines.getJSONObject(i + 1).get("text"));
            }
            if(text.contains("创建时间")){
                String timeStr = (String) lines.getJSONObject(i + 1).get("text");
                Date time;
                try {
                    // 2023-02-1511:14:25
                    time = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").parse(timeStr);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                bill.setTime(time);
            }
            if(text.contains("联系商家") || text.contains("支付备注")) {
                break;
            }
        }
        return bill;
    }

    public Bill elmBill(int index, JSONArray lines) {
        Bill bill = new Bill();

        bill.setType("餐饮");
        bill.setBillType(1);

        bill.setRemark( (String) lines.getJSONObject(index + 1).get("text"));

        for(int i = index; i < lines.size(); i++) {
            String text = (String) lines.getJSONObject(i).get("text");
            if(text.contains("下单时间：")) {
                String timeStr = text.replace("下单时间：","");
                Date time;
                try {
                    // 2023-02-12 10：54：14
                    time = new SimpleDateFormat("yyyy-MM-dd HH：mm：ss").parse(timeStr);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                bill.setTime(time);
            }
            if(text.contains("实付：¥")){
                String money = text.replace("实付：¥","");
                bill.setMoney( Double.parseDouble(money) );
                break;
            }
        }
        return bill;
    }

}
